package com.cd.system.service.impl;

import com.cd.common.dto.EchartsDto;
import com.cd.common.util.DateUtils;
import com.cd.common.util.RegexUtils;
import com.cd.system.jpa.entity.DailyUserCount;
import com.cd.system.jpa.entityImport.SysLogininfor;
import com.cd.system.jpa.entityImport.SysPost;
import com.cd.common.domain.SysRole;
import com.cd.common.domain.SysUser;
import com.cd.system.jpa.entityImport.SysUserPost;
import com.cd.system.jpa.entityImport.SysUserRole;
import com.cd.system.jpa.repository.DailyUserCountRepository;
import com.cd.system.jpa.repository.SysLoginInForRepository;
import com.cd.system.jpa.repository.UserRepository;
import com.cd.system.mapper.SysPostMapper;
import com.cd.system.mapper.SysRoleMapper;
import com.cd.system.mapper.SysUserMapper;
import com.cd.system.mapper.SysUserPostMapper;
import com.cd.system.mapper.SysUserRoleMapper;
import com.cd.common.constant.Constants;
import com.cd.common.constant.UserConstants;
import com.cd.common.domain.LoginUser;
import com.cd.common.domain.ResponseResult;
import com.cd.common.exception.LqqException;
import com.cd.system.service.SysConfigService;
import com.cd.system.service.UserService;
import com.cd.common.util.AuthUtils;
import com.cd.common.util.AuthenticationContextHolder;
import com.cd.common.util.IpUtils;
import com.cd.common.util.JwtUtils;
import com.cd.common.constant.LqqConstant;
import com.cd.common.util.LqqStatusEnum;
import com.cd.common.util.RedisCache;
import com.cd.common.util.ServletUtils;
import com.cd.common.util.SpringUtils;
import com.cd.common.util.StringUtils;
import eu.bitwalker.useragentutils.UserAgent;
import org.hibernate.service.spi.ServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl implements UserService {

    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    @Qualifier("userDao")
    private UserRepository userDao;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SysPostMapper postMapper;

    @Autowired
    private SysLoginInForRepository loginInForRepository;

    @Value("${lqq.token.expire}")
    private int tokenExpire;

    @Value("${lqq.register.permission}")
    private boolean registerPermission;

    @Value("${lqq.helloWord}")
    private String helloWord;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Autowired
    private SysUserPostMapper userPostMapper;

    @Autowired
    private SysConfigService configService;

    @Autowired
    protected Validator validator;

    @Autowired
    private DailyUserCountRepository dailyUserCountRepository;

    @PersistenceContext
    private EntityManager entityManager;


    //    public UserServiceImpl() {
//        logger.info("UserServiceImpl初始化");
//        if (helloWord==null || helloWord.trim().length()<1){
//            //throw new LqqException("欢迎词不能为空");
//            //这里实例化了 还没有注入autowired 所以拿不到值
//        }
//    }
    @PostConstruct
    public void init() {
        if (helloWord == null || helloWord.trim().length() < 1) {
            throw new LqqException("欢迎词不能为空");
        }
        logger.info("Bean注入后会自动调用该方法");//一次
    }


    @Override
    public ResponseResult login(SysUser user) {
        UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
        //AuthenticationManager authenticate进行用户认证
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
        //上面这个会调用之前loginUser的东西（X），调用的是userDetailService的

        //authenticate方法，这个方法会调用userDetailService的loadUserByUsername方法
        Authentication authenticate = null;
        try {
            authenticate = authenticationManager.authenticate(authenticationToken);
        } catch (Exception e) {
            this.recordLoginInfo(user,e.getLocalizedMessage());
            throw new LqqException(e.getLocalizedMessage());
        } finally {
            //清空上下文
            AuthenticationContextHolder.clearContext();
        }

        //如果认证没通过，给出对应的提示
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException(LqqConstant.LOGIN_FAIL);
        }
        //如果认证通过了，使用userid生成一个jwt jwt存入ResponseResult返回
        //AuthUtils.saveTokenAndGetLoginUser(authenticate, redisCache,tokenExpire);
        //这里其实有三个业务 解析user 存入token返回 记录登录记录 因为想考虑复用 单点的时候用
        //单点可以不返回jwt 但是要存登录记录
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getUser().getUserId().toString();
        String jwt = JwtUtils.createJWT(userId);
        Map<String, String> map = new HashMap<>();
        map.put(Constants.TOKEN, jwt);
        //写入登录地址等其他信息
        //loginUser.setLoginLocation(AddressUtils.getRealAddressByIP(ip));
        loginUser.setOs(userAgent.getOperatingSystem().getName());
        loginUser.setBrowser(userAgent.getBrowser().getName());
        loginUser.setToken(userId + "|" + IpUtils.getIpAddr());
        loginUser.setIpAddr(IpUtils.getIpAddr());
        loginUser.setLoginTime(new Date().getTime());

        //把完整的用户信息存入redis  userid作为key 混淆ip|  设置过期时间 3600秒
        redisCache.setCacheObject(LqqConstant.LOGINKEY_PREFIX + userId + "|" + IpUtils.getIpAddr(),
                loginUser, tokenExpire, TimeUnit.SECONDS);
        this.recordLoginInfo(user, LqqConstant.LOGIN_SUCCESS);
        //后续可以把登录信息单独抽象出来
        return new ResponseResult(200, LqqConstant.LOGIN_SUCCESS, map);
    }

    @Override
    @Transactional
    public Map SSOLogin(String username) {
        //返回对应的map
        SysUser user = userDao.selectUserByUserName(username);
        UsernamePasswordAuthenticationToken authenticationToken = null;
        if (Objects.isNull(user)) {
            //如果不存在，注册
            user =createUser(username);
            userDao.save(user);
        } else {
        }
        Map<String, String> map = createCookie(user);
        return map;
    }


    /**
     * @param user
     * @Description 用户信息修改
     * @Author lqq
     * @Date 2023/11/16 17:02
     */
    @Override
    @Transactional
    @Deprecated
    public boolean modifyUser(SysUser user) {
        Optional<SysUser> findUser = userDao.findByUserNameEquals(user.getUserName());
        if (!findUser.isPresent()) {
            return false;
        }
        //修改用户应该实实际际的修改，而不是直接使用传入的，风险太大
        SysUser operationUser = findUser.get();
        operationUser.setNickName(user.getNickName());
        operationUser.setEmail(user.getEmail());
        operationUser.setPhonenumber(user.getPhonenumber());
        operationUser.setSex(user.getSex());
//        user.setId(findUser.get().getId());
        //禁止在这里修改密码,密码沿用以前的
//        user.setPassword(findUser.get().getPassword());
        //这里要注意判空，其他值从前端传入，否则不允许修改
        return userDao.save(operationUser) != null;
    }

    /**
     * @param username
     * @Description 用户信息查询
     * @Author lqq
     * @Date 2023/11/16 17:02
     */
    @Override
    public ResponseResult userInfoByUsername(String username) {
        Optional<SysUser> byUserNameEquals = userDao.findByUserNameEquals(username);
        if (!byUserNameEquals.isPresent()) {
            return new ResponseResult(LqqStatusEnum.LQQ_USER_NOT_EXIST);
        }
        ResponseResult result = new ResponseResult(LqqStatusEnum.LQQ_SUCCESS);
        //返回不带密码的用户信息
        result.setData(byUserNameEquals.get());
        return result;
    }

    /**
     * @param id
     * @Description 用户禁用或者注销
     * @Author lqq
     * @Date 2023/11/16 17:02
     */
    @Override
    public ResponseResult disabled(Long id, Integer status) {
        Optional<SysUser> findUser = userDao.findById(id);
        if (!findUser.isPresent()) {
            return new ResponseResult(LqqStatusEnum.LQQ_USER_NOT_EXIST);
        }
        SysUser user = findUser.get();
        if (status.equals(0)) {
            user.setStatus("0");
        } else if (status.equals(1)) {
            user.setStatus("1");
        } else {
            return new ResponseResult(LqqStatusEnum.LQQ_ILLEGAL_OPERATION);
        }
        return userDao.save(user) == null ? new ResponseResult(LqqStatusEnum.LQQ_JPA_UPDATE_ERROR) : new ResponseResult(LqqStatusEnum.LQQ_SUCCESS);
    }

    /**
     * 重置用户密码
     *
     * @param user 用户信息
     * @return 操作结果
     */
    @Override
    public boolean reset(SysUser user, String newPassword) {
        // 根据用户名查询用户
//        SysUser findUser = userDao.selectUserByUserName(user.getUserName());
//        if (Objects.isNull(findUser)) {
//            return new ResponseResult(LqqStatusEnum.LQQ_USER_NOT_EXIST);
//        }

        // 更新用户密码，使用BCryptPasswordEncoder进行加密
        user.setPassword(new BCryptPasswordEncoder().encode(newPassword));

        // 保存更新后的用户信息并返回结果
        return userDao.save(user) != null;
    }

    /**
     * 注册用户
     *
     * @param user 要注册的用户对象
     * @return 注册结果的响应结果对象
     */
    @Override
    public String register(SysUser user) {
        //校验用户是否为纯数字
        if(!RegexUtils.isAlphanumeric(user.getUserName())){
            throw new LqqException(LqqStatusEnum.LQQ_USERNAME_ILLEGAL.getMsg());
        }
        user.setPassword(AuthUtils.encryptPassword(user.getPassword()));
        if (!registerPermission) {
            throw new LqqException(LqqStatusEnum.LQQ_REGISTER_DISABLE.getMsg());
        }
        //if (userDao.existsByUserNameAndDelFlagNot(user.getUserName(), "2")) {
        if (userDao.findByUserNameEquals(user.getUserName()).isPresent()) {
            logger.error("用户名已存在");
            throw new LqqException(LqqStatusEnum.LQQ_USER_EXIST.getMsg());
        }

        if (userMapper.insertUser(user) > 0){
            //记录日志
            recordLoginInfo(user, "注册成功");
            //默认添加魔法卡牌权限以及其他权限
            Long[] roleIds = new Long[]{6L};
            this.insertUserRole(user.getUserId(),roleIds);
            return "";
        }else {
            return  "注册失败,请联系系统管理人员";
        }
    }

    /**
     * 根据用户名查找用户
     *
     * @param admin 用户名
     * @return 用户对象，如果未找到则返回null
     */
    @Override
    public SysUser findByUsername(String admin) {
        Optional<SysUser> userNameEquals = userDao.findByUserNameEquals(admin);
        return userNameEquals.isPresent() ? userNameEquals.get() : null;
    }

    /**
     * 记录登录信息以及登录记录
     *
     * @param user    用户
     * @param Message 要记录的信息
     */
    @Override
    public void recordLoginInfo(SysUser user, String Message) {
        //操作记录
        UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
        //创建登录信息
        SysLogininfor sysLoginInfo = new SysLogininfor();
        sysLoginInfo.setUserName(user.getUserName());
        sysLoginInfo.setIpaddr(IpUtils.getIpAddr());
        sysLoginInfo.setLoginTime(new Date());
        sysLoginInfo.setStatus(loginInforStatus(Message));
        sysLoginInfo.setBrowser(userAgent.getBrowser().getName());
        sysLoginInfo.setOs(userAgent.getOperatingSystem().getName());
        sysLoginInfo.setMsg(Message);
        //记录登录信息
        loginInForRepository.save(sysLoginInfo);
    }

    private String loginInforStatus(String message) {
        if (message.equals(LqqConstant.LOGIN_FAIL) ||
                message.equals(LqqConstant.USER_NAME_OR_PASSWORD_ERROR) ||
                message.equals(LqqConstant.TOKEN_ILLEGAL) ||
                message.equals(LqqConstant.LOGIN_UNAUTHORIZED)
        ) {
            return "1";
        }
        return "0";
    }

    /**
     * 根据条件分页查询用户列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    public List<SysUser> selectUserList(SysUser user) {
        return userMapper.selectUserList(user);
    }

    /**
     * 根据条件分页查询已分配用户角色列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    public List<SysUser> selectAllocatedList(SysUser user) {
        return userMapper.selectAllocatedList(user);
    }

    /**
     * 根据条件分页查询未分配用户角色列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    public List<SysUser> selectUnallocatedList(SysUser user) {
        return userMapper.selectUnallocatedList(user);
    }

    /**
     * 通过用户名查询用户
     *
     * @param userName 用户名
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserByUserName(String userName) {
        return userMapper.selectUserByUserName(userName);
    }

    /**
     * 通过用户ID查询用户
     *
     * @param userId 用户ID
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserById(Long userId) {
        return userMapper.selectUserById(userId);
    }

    /**
     * 查询用户所属角色组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserRoleGroup(String userName) {
        List<SysRole> list = roleMapper.selectRolesByUserName(userName);
        if (CollectionUtils.isEmpty(list)) {
            return StringUtils.EMPTY;
        }
        return list.stream().map(SysRole::getRoleName).collect(Collectors.joining(","));
    }

    /**
     * 查询用户所属岗位组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserPostGroup(String userName) {
        List<SysPost> list = postMapper.selectPostsByUserName(userName);
        if (CollectionUtils.isEmpty(list)) {
            return StringUtils.EMPTY;
        }
        return list.stream().map(SysPost::getPostName).collect(Collectors.joining(","));
    }

    /**
     * 校验用户名称是否唯一
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean checkUserNameUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkUserNameUnique(user.getUserName());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验手机号码是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public boolean checkPhoneUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkPhoneUnique(user.getPhonenumber());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验email是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public boolean checkEmailUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkEmailUnique(user.getEmail());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验用户是否允许操作
     *
     * @param user 用户信息
     */
    @Override
    public void checkUserAllowed(SysUser user) {
        if (StringUtils.isNotNull(user.getUserId()) && user.isAdmin()) {
            throw new ServiceException("不允许操作超级管理员用户");
        }
    }

    /**
     * 校验用户是否有数据权限
     *
     * @param userId 用户id
     */
    @Override
    public void checkUserDataScope(Long userId) {
        if (!SysUser.isAdmin(AuthUtils.getLoginUser().getUser().getUserId())) {
            SysUser user = new SysUser();
            user.setUserId(userId);
            List<SysUser> users = SpringUtils.getAopProxy(this).selectUserList(user);
            if (StringUtils.isEmpty(users)) {
                throw new ServiceException("没有权限访问用户数据！");
            }
        }
    }

    /**
     * 新增保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertUser(SysUser user) {
        // 新增用户信息
        int rows = userMapper.insertUser(user);
        // 新增用户岗位关联
        insertUserPost(user);
        // 新增用户与角色管理
        insertUserRole(user);
        return rows;
    }


    /**
     * 修改保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateUser(SysUser user) {
        Long userId = user.getUserId();
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 新增用户与角色管理
        insertUserRole(user);
        // 删除用户与岗位关联
        userPostMapper.deleteUserPostByUserId(userId);
        // 新增用户与岗位管理
        insertUserPost(user);
        return userMapper.updateUser(user);
    }

    /**
     * 用户授权角色
     *
     * @param userId  用户ID
     * @param roleIds 角色组
     */
    @Override
    @Transactional
    public void insertUserAuth(Long userId, Long[] roleIds) {
        userRoleMapper.deleteUserRoleByUserId(userId);
        insertUserRole(userId, roleIds);
    }

    /**
     * 修改用户状态
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserStatus(SysUser user) {
        return userMapper.updateUser(user);
    }

    /**
     * 修改用户基本信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserProfile(SysUser user) {
        return userMapper.updateUser(user);
    }

    /**
     * 修改用户头像
     *
     * @param userName 用户名
     * @param avatar   头像地址
     * @return 结果
     */
    @Override
    public boolean updateUserAvatar(String userName, String avatar) {
        return userMapper.updateUserAvatar(userName, avatar) > 0;
    }

    /**
     * 重置用户密码
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int resetPwd(SysUser user) {
        return userMapper.updateUser(user);
    }

    /**
     * 重置用户密码
     *
     * @param userName 用户名
     * @param password 密码
     * @return 结果
     */
    @Override
    public int resetUserPwd(String userName, String password) {
        return userMapper.resetUserPwd(userName, password);
    }

    /**
     * 新增用户角色信息
     *
     * @param user 用户对象
     */
    public void insertUserRole(SysUser user) {
        this.insertUserRole(user.getUserId(), user.getRoleIds());
    }

    /**
     * 新增用户岗位信息
     *
     * @param user 用户对象
     */
    public void insertUserPost(SysUser user) {
        Long[] posts = user.getPostIds();
        if (StringUtils.isNotEmpty(posts)) {
            // 新增用户与岗位管理
            List<SysUserPost> list = new ArrayList<SysUserPost>(posts.length);
            for (Long postId : posts) {
                SysUserPost up = new SysUserPost();
                up.setUserId(user.getUserId());
                up.setPostId(postId);
                list.add(up);
            }
            userPostMapper.batchUserPost(list);
        }
    }

    /**
     * 新增用户角色信息
     *
     * @param userId  用户ID
     * @param roleIds 角色组
     */
    public void insertUserRole(Long userId, Long[] roleIds) {
        if (StringUtils.isNotEmpty(roleIds)) {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>(roleIds.length);
            for (Long roleId : roleIds) {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(userId);
                ur.setRoleId(roleId);
                list.add(ur);
            }
            userRoleMapper.batchUserRole(list);
        }
    }

    /**
     * 通过用户ID删除用户
     *
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteUserById(Long userId) {
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 删除用户与岗位表
        userPostMapper.deleteUserPostByUserId(userId);
        return userMapper.deleteUserById(userId);
    }

    /**
     * 批量删除用户信息
     *
     * @param userIds 需要删除的用户ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteUserByIds(Long[] userIds) {
        for (Long userId : userIds) {
            checkUserAllowed(new SysUser(userId));
            checkUserDataScope(userId);
        }
        // 删除用户与角色关联
        userRoleMapper.deleteUserRole(userIds);
        // 删除用户与岗位关联
        userPostMapper.deleteUserPost(userIds);
        return userMapper.deleteUserByIds(userIds);
    }

    /**
     * 导入用户数据
     *
     * @param userList        用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName        操作用户
     * @return 结果
     */
    @Override
    public String importUser(List<SysUser> userList, Boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(userList) || userList.size() == 0) {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        String password = configService.selectConfigByKey("sys.user.initPassword");
        for (SysUser user : userList) {
            try {
                // 验证是否存在这个用户
                SysUser u = userMapper.selectUserByUserName(user.getUserName());
                if (StringUtils.isNull(u)) {
                    //Bean对象属性验证
                    validateWithException(validator, user);
                    user.setPassword(AuthUtils.encryptPassword(password));
                    user.setCreateBy(operName);
                    userMapper.insertUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 导入成功");
                } else if (isUpdateSupport) {
                    //Bean对象属性验证
                    validateWithException(validator, user);
                    checkUserAllowed(u);
                    checkUserDataScope(u.getUserId());
                    user.setUserId(u.getUserId());
                    user.setUpdateBy(operName);
                    userMapper.updateUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、账号 " + user.getUserName() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + user.getUserName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                logger.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * @Description 记录每天用户数量
     * @Author lqq
     * @Date 2025/3/27 10:29
     **/
    @Override
    public boolean recordUserCount() {
        long count = userDao.count();
        DailyUserCount dailyUserCount = new DailyUserCount();
        dailyUserCount.setCount(count);
        dailyUserCount.setDate(DateUtils.getDate());
        dailyUserCountRepository.save(dailyUserCount);
        return true;
    }

    /**
     * @Description 获取最近用户数量信息。
     * @Author lqq
     * @Date 2025/3/27 10:29
     **/
    @Override
    public EchartsDto getDailyUserCount() {
        String sql = "SELECT * FROM sys_daily_user_count sduc ORDER BY sduc.date DESC LIMIT 15"; // 原生 SQL 查询
        Query query = entityManager.createNativeQuery(sql, DailyUserCount.class);
        //query.setParameter("limit", 15); // 设置参数
        List<DailyUserCount> all=query.getResultList();
        // = dailyUserCountRepository.findAll();
        EchartsDto echartsDto = new EchartsDto();
        for (DailyUserCount dailyUserCount : all) {
            echartsDto.getXData().add(dailyUserCount.getDate());
            echartsDto.getYData().add(dailyUserCount.getCount());
        }
        //反转列表顺序方便展示
        Collections.reverse(echartsDto.getXData());
        Collections.reverse(echartsDto.getYData());
        //一天一条 理论十年都不会有性能瓶颈
        return echartsDto;
    }

    @Override
    public ResponseResult quickLogin(Long[] roleIds) {
        int failedCount=0;
        String randomUsername =AuthUtils.generateRandomString();
        SysUser user = new SysUser();
        while(userDao.findByUserNameEquals(randomUsername).isPresent()) {
            //如果生成失败 则重新生成
            randomUsername =AuthUtils.generateRandomString();
            if (failedCount>5){
                throw new LqqException("人数太多了，请再试一次~");
            }
            failedCount++;

        }
        user.setUserName(randomUsername);
        user.setPassword(AuthUtils.encryptPassword(randomUsername));
        user.setCreateBy("游客登录");

        if (!registerPermission) {
            throw new LqqException(LqqStatusEnum.LQQ_REGISTER_DISABLE.getMsg());
        }


        if (userMapper.insertUser(user) > 0){
            //记录日志
            recordLoginInfo(user, "注册成功");
            //默认添加权限 目前写死 考虑可扩展的话 可以让前端传入权限名称
            this.insertUserRole(user.getUserId(),roleIds);
        }
        //恢复密码 方便下面使用
        user.setPassword(randomUsername);
        UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
        //AuthenticationManager authenticate进行用户认证
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
        //上面这个会调用之前loginUser的东西（X），调用的是userDetailService的

        //authenticate方法，这个方法会调用userDetailService的loadUserByUsername方法
        Authentication authenticate = null;
        try {
            authenticate = authenticationManager.authenticate(authenticationToken);
        } catch (Exception e) {
            this.recordLoginInfo(user,e.getLocalizedMessage());
            throw new LqqException(e.getLocalizedMessage());
        } finally {
            //清空上下文
            AuthenticationContextHolder.clearContext();
        }

        //如果认证没通过，给出对应的提示
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException(LqqConstant.LOGIN_FAIL);
        }
        //如果认证通过了，使用userid生成一个jwt jwt存入ResponseResult返回
        //AuthUtils.saveTokenAndGetLoginUser(authenticate, redisCache,tokenExpire);
        //这里其实有三个业务 解析user 存入token返回 记录登录记录 因为想考虑复用 单点的时候用
        //单点可以不返回jwt 但是要存登录记录
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getUser().getUserId().toString();
        String jwt = JwtUtils.createJWT(userId);
        Map<String, String> map = new HashMap<>();
        map.put(Constants.TOKEN, jwt);
        //写入登录地址等其他信息
        //loginUser.setLoginLocation(AddressUtils.getRealAddressByIP(ip));
        loginUser.setOs(userAgent.getOperatingSystem().getName());
        loginUser.setBrowser(userAgent.getBrowser().getName());
        loginUser.setToken(userId + "|" + IpUtils.getIpAddr());
        loginUser.setIpAddr(IpUtils.getIpAddr());
        loginUser.setLoginTime(new Date().getTime());

        //把完整的用户信息存入redis  userid作为key 混淆ip|  设置过期时间 3600秒
        redisCache.setCacheObject(LqqConstant.LOGINKEY_PREFIX + userId + "|" + IpUtils.getIpAddr(),
                loginUser, tokenExpire, TimeUnit.SECONDS);
        this.recordLoginInfo(user, LqqConstant.LOGIN_SUCCESS);
        //后续可以把登录信息单独抽象出来
        return new ResponseResult(200, LqqConstant.LOGIN_SUCCESS, map);
    }

    private void validateWithException(Validator validator, Object object, Class<?>... groups) {
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
        if (!constraintViolations.isEmpty()) {
            throw new ConstraintViolationException(constraintViolations);
        }
    }

    /**
     * @Description 创建单点登录用户
     * @Author lqq
     * @Date 2024/9/28 14:07
     **/
    private SysUser createUser(String username) {
        SysUser user = new SysUser();
        user.setUserName(username);
        user.setPassword(new BCryptPasswordEncoder().encode(username+"sso"));
        user.setEmail(username+"@lqq.com");
        user.setCreateBy("sso");
        user.setDelFlag("0");
        user.setCreateTime(new Date());
        user.setStatus("0");
        //手机号有唯一校验 但目前可为空
        return user;
    }

    /**
     * @Description
     * @Author lqq
     * @Date 2024/9/28
     **/
    private Map<String, String> createCookie(SysUser user) {
        UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
        //正常校验
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getUser().getUserId().toString();
        String jwt = JwtUtils.createJWT(userId);
        Map<String, String> map=new HashMap<>();
        map.put(Constants.TOKEN, jwt);

        loginUser.setOs(userAgent.getOperatingSystem().getName());
        loginUser.setBrowser(userAgent.getBrowser().getName());
        loginUser.setToken(userId + "|" + IpUtils.getIpAddr());
        loginUser.setIpAddr(IpUtils.getIpAddr());
        loginUser.setLoginTime(new Date().getTime());
        //把完整的用户信息存入redis  userid作为key
        redisCache.setCacheObject(LqqConstant.LOGINKEY_PREFIX + userId + "|" + IpUtils.getIpAddr(),
                loginUser, tokenExpire, TimeUnit.SECONDS);
        this.recordLoginInfo(user, LqqConstant.LOGIN_SUCCESS);
        redisCache.setCacheObject("login:" + userId, loginUser);
        redisCache.expire("login:" + userId, tokenExpire, TimeUnit.SECONDS);
        return map;
    }

}
